import router from "./index";
import store from "../store"

router.beforeEach((to, from, next) => {
    const whiteList = ['/login'] // 白名单
    let token = store.getters.GET_TOKEN;
    let hasRoutes = store.state.hasRoutes;
    let menuList = store.getters.GET_MENU_LIST;
    if (token) {
        if (!hasRoutes) {
            generateRoutes(menuList)
            store.commit('SET_ROUTER_STATE', true)
        }
        console.log(router.getRoutes(), '打印路由1')
        next();
    } else {
        if (whiteList.includes(to.path)) {
            next();
        } else {
            next("/login")
        }
    }
})

//动态添加路由
export function generateRoutes() {
    const _asyncRoutes = store.getters.GET_MENU_LIST
    if (_asyncRoutes == null)
        return
    _asyncRoutes.forEach(menu => {
        if (menu.childMenu) {
            menu.childMenu.forEach(m => {
                let route = menuToRoute(m, menu.name);
                if (route) {
                    router.addRoute(route)
                }
            })
        }
    })
}

// 菜单路由转成对象
const menuToRoute = (menu, parentName) => {
    if (!menu.component) {
        return null;
    } else {
        let route = {
            name: menu.name,
            path: menu.path,
            meta: {
                parentName: parentName
            }
        }
        // route.component = () => import('../views/' + menu.component + '.vue');
        route.component = () => import('../views/' + menu.component + '.vue');
        return route;
    }
}